class NhatKy < ActiveRecord::Base
  attr_accessible :Tai_san_id, :PhongDen_id, :PhongDi_id, :NgayDi, :NgayTraVe, :SoLuong
  belongs_to :tai_san, :foreign_key =>  "Tai_san_id", :class_name => "TaiSan", :inverse_of => :nhat_kies
  belongs_to :phong_den, :foreign_key => "PhongDen_id", :class_name => "Phong", :inverse_of => :nhat_ky_den
  belongs_to :phong_di, :foreign_key => "PhongDi_id", :class_name => "Phong", :inverse_of => :nhat_ky_di

  def self.check_SL(sluong, id)
    if (sluong > TaiSan.find_by_MaTS(id).SLuong)
      return false
    else
      return true
    end
  end

  def self.getDSHD(tsid,chon,ngaychon,ngaychon2)
    ds = NhatKy.where(:Tai_san_id => tsid)
      if chon == "1" and ngaychon != nil
        nk = ds.where("NgayTraVe <= ?",ngaychon.to_date)
      elsif chon == "2" and ngaychon != nil
        nk = ds.where("NgayTraVe > ? or (NgayDi is null AND NgayTraVe <= ?)",ngaychon.to_date,ngaychon.to_date)
      elsif chon == "3"
        nk = ds.where("(NgayTraVe >= ? OR NgayDi >= ? OR (NgayDi is null AND NgayTraVe >= ? ) AND (NgayTraVe <= ? OR NgayDi <= ?) ",ngaychon.to_date,ngaychon.to_date,ngaychon.to_date,ngaychon2.to_date,ngaychon2.to_date)
      end
    return hash = nk.collect { |h| {:PhongDi => nil, :PhongDen => h.phong_den.TenPhongg, :NgayDi => h.NgayDi, :NgayDen => h.NgayTraVe, :SoLuong => h.SoLuong } }
  end
end
